# -*- encoding: utf-8 -*-
import time
from odoo import models, api, fields, _
from odoo import tools
from odoo.exceptions import UserError
#import odoo.addons.decimal_precision as dp
from odoo.tools import float_compare, float_round
from odoo.addons import base_cw


class account_voucher_line_query(models.Model):
    _name = 'account.voucher.line.query'
    _description = u'会计凭证明细查询'
    _auto = False

    name = fields.Char(u'单据编号', default=False)
    date = fields.Date(u'单据日期')
    voucher_category_id = fields.Many2one('account.voucher.category', u'凭证类别', required=False, ondelete="restrict")
    voucher_line_id = fields.Many2one('account.voucher.line', string='凭证明细')
    origin = fields.Char(u'来源单据', default=False)
    account_voucher_id = fields.Many2one('account.voucher', u'会计凭证', required=False)
    dc_type = fields.Selection([('D', u'借'), ('C', u'贷')], u'借贷', readonly=False, default='D')
    account_id = fields.Many2one('cncw.account', u'会计科目', required=False)
    currency_id = fields.Many2one('res.currency', u'币别', required=False)
    sub_account_id = fields.Many2one('res.partner', u'辅助核算', required=False)
    sub_account_lines_str = fields.Char(related='voucher_line_id.sub_account_lines_str',string=u'辅助核算', required=False)
    account_name = fields.Char(u'摘要', default=False)
    debit = fields.Float(u'借方金额', digits='Amount')
    credit = fields.Float(u'贷方金额', digits='Amount')


    # 会计凭证明细查询
    def init(self):
        tools.drop_view_if_exists(self._cr, 'account_voucher_line_query')
        self._cr.execute("""
            create or replace view account_voucher_line_query as (
            select a.id as id,b.name ||'-'|| a.sequence as name, b.date,b.voucher_category_id,a.id as voucher_line_id,
                b.origin,b.id as account_voucher_id,
                a.dc_type,a.account_id,a.currency_id,a.sub_account_id,
                a.name account_name,coalesce(a.debit,0) debit,coalesce(a.credit,0) credit
            from account_voucher_line a
            left join account_voucher b on a.master_id=b.id
            left join sub_account_line c on a.id=c.voucher_line_id
            where b.state='audited'
             )""")
